import React, {
  useCallback,
  useEffect,
  useState,
  useRef,
  useImperativeHandle
} from "react";
import { connect } from "react-redux";

import style from "./index.css";
import {
  setCurrentsong,
  setCurrentDetailAct,
  setCurrentSongNewAct,
  setCurrentTime
} from "@/redux/actions";
import { getTime } from "../../utils/date";

const SongItem = ({ song, playsongs, currentSongDetail }) => {
  const playsongsFun = () => {
    playsongs();
  };
  return (
    <div
      className={[
        style.songitem,
        currentSongDetail.id === song.id ? style.songAvtive : "",
      ].join(" ")}
      onClick={playsongsFun}
    >
      {currentSongDetail.id === song.id ? (
        <img
          src={require("./Icon/itemPlay.svg").default}
          alt="itemPlay"
          className={style.itemplay}
        />
      ) : null}
      <div className={style.songname}>{song.name}</div>
      <div className={style.songAuthor}>
        {song.ar
          ? song.ar.map((arname) => <div key={arname.id}>{arname.name}</div>)
          : null}
      </div>
      <div>{getTime(song.dt, 2)}</div>
      <img
        src={require("./Icon/lianjie.svg").default}
        alt="链接"
        className={style.ljIcon}
      />
    </div>
  );
};

const LrcContainer = ({
  lrcNamesArr,
  lrcTimesArr,
  currentTime,
  scrollActiveFun,
  setCurrentTimeAct,
  soundCloudAudio,
  cRef
}) => {
  const lrcRef = useRef(null)
  
  const [currentIndex, setCurrentIndex] = useState(0)
  const [canScroll, setCanScroll] = useState(true)
  
  useEffect(() => {
    
    let times = lrcTimesArr || []
    let ct = parseInt(currentTime * 1000)
    let index = times.findIndex((e,i) => {
      if (ct>=e && ct<times[i+1]) {
        // console.log('找到了 playerListTop index = ' + i);
        return true
      }else{
        // console.log('没找到 playerListTop index = ' + i);
        return false
      }
    })
    
    setCurrentIndex(index)
    // scrollActive(0)
    scrollActive(index)
    
    // if (canScroll && soundCloudAudio.audio.playing) {
    //   scrollActive(index)
    // }

  }, [lrcNamesArr, lrcTimesArr, currentTime])

  useImperativeHandle(cRef, () => ({
    // changeVal 就是暴露给父组件的方法
    canscrollChange: () => {
      lrcItemScrollInChild();
    }
  }));
  
  const scrollActive = useCallback((index) => {
    scrollActiveFun(index)
  }, [lrcNamesArr, lrcTimesArr, currentTime])

  const updateCurrentIndex = useCallback((i) => {
    console.log(i, 'i');
    let currentTime = lrcTimesArr[i] / 1000
    soundCloudAudio.audio.currentTime = currentTime
    // setCurrentTimeAct(parseInt(currentTime / 1000))
    // setCurrentIndex(i)
    // scrollActive(i)
    
  }, [lrcTimesArr, soundCloudAudio])

  /*
    - 如何解决播放音乐时滚动失效的问题
    1. 滚动开始，关闭寻找下标的方法
      - 实践：将该方法加入一个参数
    2. 滚动结束，设置定时器，两秒后自动开启这个参数
      - 组件根据currentTime再次渲染
  */

  const lrcItemScrollInChild = useCallback(() => {
    if (!canScroll) {
      return
    }
    console.log('setCanScroll(false)');
    setCanScroll(false)
    console.log(canScroll, 'setCanScroll');

    // setTimeout(() => {
    //   console.log('setCanScroll(true)');
    //   setCanScroll(true)
    // }, 2000)
  }, [])

  return (
    <div className={style.lrcNamesItem}>
      {lrcNamesArr
        ? lrcNamesArr.map((item, index) => (
            item ? <div className={index == currentIndex ? style.nameActive : null} key={index} onClick={() => updateCurrentIndex(index)}>{item}</div>
            : <div style={{color: 'transparent'}} key={index}>nodata</div>
          ))
        : null}
    </div>
  );
};

const PlayerListTop = ({
  songsList = [],
  currentSongDetail,
  playSongGlobal,
  sendlrcDetail,
  currentTime,
  listTopRef,
  lrcTimesArr,
  lrcNamesArr,
  setCurrentTimeAct,
  soundCloudAudio,
  toggleShowPlaylist
}) => {
  const [clickTime, setClickTime] = useState("done");
  const lrcbodyRef = useRef(null)
  const childRef = useRef(null)
  

  const scrollActive = useCallback((index) => {
    if (index < 0) {
      return
    }
    let scrollTop = parseInt(index * 28) - 100
    lrcbodyRef.current.scrollTop = scrollTop
    
    // console.log(lrcbodyRef.current.animate, 'lrcbodyRef.current.animate')
    // console.log(lrcbodyRef, 'lrcbodyRef');
    // console.log(lrcbodyRef.current.scrollTop, 'lrcbodyRef.current.srcollTop');
  }, [lrcbodyRef])

  const playsongs = useCallback(
    async (song) => {
      console.log("playsongs", song);
      // 添加点击次数节流
      if (clickTime != "done") {
        console.log("重复点击!");
        return;
      }
      setClickTime("doing");
      setClickTime("done");
      playSongGlobal(song);
    },
    [songsList, clickTime]
  );

  const lrcItemScroll = () => {
    childRef.current.canscrollChange();
  }

  return (
    <div className={style.containter}>
      <div className={style.listContent}>
        <div className={style.listHeader}>
          <div className={style.listTitle}>播放列表({songsList.length})</div>
          <div className={style.listStar}>
            <img src={require("./Icon/star.svg").default} alt="收藏" />
            收藏全部
          </div>
          <div className={style.listStar}>
            <img src={require("./Icon/clear.svg").default} alt="清除" />
            清除
          </div>
        </div>
        <div className={style.listBody}>
          {songsList.length > 0
            ? songsList.map((song, index) => (
                <SongItem
                  currentSongDetail={currentSongDetail}
                  song={song}
                  key={song.id}
                  playsongs={() => playsongs(song)}
                  index={index}
                />
              ))
            : null}
        </div>
      </div>
      <div className={style.lrcContent}>
        <div className={style.lrcHeader}>{currentSongDetail.name}</div>
        <div className={style.lrcBody} ref={lrcbodyRef} onScroll={lrcItemScroll}>
          {sendlrcDetail ? (
            <LrcContainer
              sendlrcDetail={sendlrcDetail}
              currentTime={currentTime}
              listTopRef={listTopRef}
              lrcTimesArr={lrcTimesArr}
              lrcNamesArr={lrcNamesArr}
              scrollActiveFun={scrollActive}
              setCurrentTimeAct={setCurrentTimeAct}
              soundCloudAudio={soundCloudAudio}
              cRef={childRef}
            />
          ) : (
            // <div>{sendlrcDetail.lyric}</div>
            <div className={style.noLrc}>纯音乐，无歌词</div>
          )}
        </div>
      </div>
      <div className={style.closeIcon} onClick={() => toggleShowPlaylist()}>
        <img src={require('./Icon/close.svg').default} alt="关闭" width="20" height="20"/>
      </div>
    </div>
  );
};

const mstate = (state) => {
  // console.log(state, 'state');
  return {
    currentSongDetail: state.currentDoingInfo.currentSongDetail,
    sendlrcDetail: state.currentDoingInfo.sendlrcDetail,
    currentTime: state.playerChangeData.currentTime,
    lrcTimesArr: state.currentDoingInfo.lrcArrTotal.lrcTimesArr,
    lrcNamesArr: state.currentDoingInfo.lrcArrTotal.lrcNamesArr,
  };
};
const mdispatch = (dispatch) => {
  return {
    setCurrentSong: (data) => {
      dispatch(setCurrentsong(data));
    },
    setCurrentSongDetail: (data) => {
      dispatch(setCurrentDetailAct(data));
    },
    setNewSongs: (data) => {
      dispatch(setCurrentSongNewAct(data));
    },
    setCurrentTimeAct: (data) => {
      dispatch(setCurrentTime(data))
    },
  };
};
export default connect(mstate, mdispatch)(PlayerListTop);
